package com.example.onlinemusic.controller;

import com.example.onlinemusic.mapper.UserMapper;
import com.example.onlinemusic.model.User;
import com.example.onlinemusic.tools.Constant;
import com.example.onlinemusic.tools.ResponseBodyMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * Created with IntelliJ IDEA.
 * Description:登录模块
 * User: LXW
 * Date: 2022-07-23
 * Time: 18:09
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    public UserController() {
    }

    @RequestMapping("/login")
    public ResponseBodyMessage<User> login(@RequestParam String username, @RequestParam String password,
                                           HttpServletRequest request) {
        User user = userMapper.selectByName(username);
        // 如果查询到的用户名为空则登陆失败
        if(user == null) {
            System.out.println("登陆失败");
            return new ResponseBodyMessage<User>(-1, "用户名或密码错误", user);
        }else {
         // 不为空则进行密码的校验
            boolean flag= bCryptPasswordEncoder.matches(password, user.getPassword());
            if(!flag) {
                return new ResponseBodyMessage<User>(-1, "用户名或密码错误", user);
            }
            request.getSession().setAttribute(Constant.USERINFO_SESSION_KEY,user);
            return new ResponseBodyMessage<User>(200, "登陆成功", user);
        }
    }
}
